package com.asen.commons.core.base.service.impl;

import com.asen.commons.core.base.domain.EnableBase;
import com.asen.commons.core.base.enums.ActionTypeEnum;
import com.asen.commons.core.base.service.EnableBaseService;
import com.asen.commons.core.listener.ServiceContext;
import com.asen.commons.utils.BaseAssert;
import com.asen.commons.utils.IdUtils;
import org.springframework.transaction.annotation.Transactional;

/**
 * 基础资料Service抽象类
 *
 * @author Gary
 * @version 1.0
 * @date 2018-12-09
 */
public abstract class AbstractEnableBaseServiceImpl<T extends EnableBase> extends AbstractGenericServiceImpl<T> implements EnableBaseService<T> {

    @Override
    protected void beforeAdd(T model) throws Exception {
        super.beforeAdd(model);

        if (model.getIsEnabled() == null) {
            // 新增默认启用
            model.setIsEnabled(Boolean.TRUE);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void enable(Long id) throws Exception {
        BaseAssert.check(IdUtils.isNotEmpty(id), "参数id不能为空");
        T model = this.get(id);
        beforeEnable(model);
        ServiceContext serviceContext = createServiceContext(model, ActionTypeEnum.ENABLE);
        beforeListener(serviceContext);

        model.setIsEnabled(true);
        updatePartial(model, "isEnabled");

        afterEnable(model);
        afterListener(serviceContext);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void disable(Long id) throws Exception {
        BaseAssert.check(IdUtils.isNotEmpty(id), "参数id不能为空");
        T model = this.get(id);
        beforeDisable(model);
        ServiceContext serviceContext = createServiceContext(model, ActionTypeEnum.DISABLE);
        beforeListener(serviceContext);

        model.setIsEnabled(false);
        updatePartial(model, "isEnabled");

        afterDisable(model);
        afterListener(serviceContext);
    }

    protected void beforeEnable(T model) throws Exception {

    }

    protected void afterEnable(T model) throws Exception {

    }

    protected void beforeDisable(T model) throws Exception {

    }

    protected void afterDisable(T model) throws Exception {

    }
}
